const express = require('express')
const router = express.Router()
const request = require('request-promise')

router.get('/', (req, res, next) => {
  res.render('index')
})

router.get('/trade', async (req, res, next) => {
  let exchange = req.query.exchange || '火币Pro'
  let currency = req.query.currency || 'USDT'
  let list = await getTrade(exchange, currency)
  console.log(list)
  res.json({code: 0, message: '请求成功', data: {list: list || []}})
})

/**
 * 获取行情
 * @param {string} exchange - 交易所
 * @param {string} currency - 交易对
 * @returns {Promise.<*>}
 */
async function getTrade (exchange, currency) {
  try {
    let res = await request({
      method: 'GET',
      url: 'https://api.finbtc.net/app/short/list/all',
      qs: {publishAt: Date.now()},
      headers: {
        'x-app-info': '1.6.0/meizu/android'
      },
      json: true
    })
    if (res.code === 0) {
      console.log(res.data.items)
      if (currency === 'all') {
        return res.data.items.filter(item => item.exchange === exchange && (item.type === '急速拉升' || item.type === '快速反弹'))
      } else {
        return res.data.items.filter(item => item.exchange === exchange && item.targetSymbol === currency && (item.type === '急速拉升' || item.type === '快速反弹'))
      }
    } else {
      throw new Error(res.msg)
    }
  } catch (e) {
    return null
  }
}

module.exports = router
